<?php
class UserSubstitution_Controller extends AdminController {

    public function __construct() {
        parent::__construct('seminar');
        // $this->setDefaultListOrder('begin_date');
        // $this->contentLayout = 'user/userLayout';
    }

    public function index() {
        return $this->edit();
    }

    public function edit() {
        $formData = array();
        $this->loadFormData();
        $this->viewData['formData'] = $formData;
        $this->renderSubview('/admin/substituteUser');
    }

    public function loadFormData() {
        $this->viewData['personOptions'] = $this->dao->queryOptions(
                'SELECT id, first_name, last_name, birth_date FROM person ' .
                'WHERE id != :id ' .
                'ORDER BY last_name ASC, first_name ASC, birth_date ASC',
                array('id' => $this->getAuthUser('id')), array(' ', '()'));
    }

    public function substitute() {
    	$personId = $this->input->post('person_id');
    	if (! $personId) {
    		$personId = $this->input->get('person_id');
    	}

        // Basic validation
    	if (! $personId) {
    		$this->msg->error('error.invalidId');
    	}

        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/substituteUser');
            return;
        }
        
        $person = $this->dao->getById('person', $personId);
        if (! $person) {
            $this->loadFormData();
            $this->msg->error('substituteUser.error-userNotFound');
            $this->publishErrors('admin/substituteUser');
            return;
        }

        $this->getSessionData()->clearUserSpaceData();
        $this->getSessionData()->setUserSubstitute($person);
        logger::securityInfo('Became person #' . $person['id'] . ' ' . format::personFullName($person) . '.');
        $this->msg->info('userSpace-substitutionSuccess', format::personFullName($person));
        $this->redirect('/user/userSpace');
    }

    public function cancelSubstitution() {
    	$this->getSessionData()->clearUserSpaceData();
    	$person = $this->getSessionData()->getUserSubstitute();
        $this->getSessionData()->setUserSubstitute(NULL);
        logger::securityInfo('Stopped being person #' . $person['id'] . ' ' . format::personFullName($person) . '.');
        $this->msg->info('userSpace-substitutionCancelled');
        $this->redirect('/admin/adminSpace');
    }
}
